<template>
	<view class="auth-container">
		<!-- 用户信息表单 -->
		<view class="form-section">
			<view class="form-item">
				<text class="label">姓名</text>
				<input class="input" type="text" placeholder="请输入真实姓名" v-model="form.realName" maxlength="20" />
			</view>

			<view class="form-item">
				<text class="label">身份证号</text>
				<input class="input" type="idcard" placeholder="请输入身份证号码" v-model="form.idCard" maxlength="18" />
			</view>
		</view>

		<!-- 认证按钮 -->
		<button class="auth-button" type="primary" @click="startAuth" :disabled="loading">
			{{ loading ? '认证中...' : '开始实人认证' }}
		</button>

		<!-- 认证结果 -->
		<view class="result-section" v-if="authResult">
			<view class="result-title">认证结果</view>
			<view class="result-content" :class="resultClass">
				{{ authResult.message || authResult }}
			</view>
			<view class="result-detail" v-if="authResult.certifyId">
				流水号: {{ authResult.certifyId }}
			</view>
		</view>

		<!-- 平台说明 -->
		<view class="platform-info">
			<text class="info-text">当前平台: {{ platform }}</text>
			<text class="info-text">认证方式: {{ authMethod }}</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				platform: '',
				authMethod: '',
				form: {
					realName: '',
					idCard: ''
				},
				loading: false,
				authResult: null,
				resultClass: ''
			}
		},

		onLoad(options) {
			// 检测平台并设置认证方式
			this.detectPlatform();

			// 检查H5回调参数
			this.checkH5Callback(options);
		},

		methods: {
			// 检测运行平台
			detectPlatform() {
				// #ifdef H5
				this.platform = 'H5';
				this.authMethod = '跳转认证页面';
				// #endif

				// #ifdef MP-WEIXIN
				this.platform = '微信小程序';
				this.authMethod = '原生刷脸界面';
				// #endif

				// #ifdef APP-PLUS
				this.platform = 'App';
				this.authMethod = '原生刷脸界面';
				// #endif

				console.log(`运行平台: ${this.platform}, 认证方式: ${this.authMethod}`);
			},

			// 开始认证流程
			async startAuth() {
				if (this.loading) return;

				if (!this.validateForm()) {
					return;
				}

				this.loading = true;
				this.authResult = null;

				try {
					// #ifdef H5
					await this.h5Auth();
					// #endif

					// #ifdef MP-WEIXIN || APP-PLUS
					await this.nativeAuth();
					// #endif

				} catch (error) {
					console.error('认证流程异常:', error);
					this.showError('认证失败，请稍后重试');
				} finally {
					this.loading = false;
				}
			},

			// H5平台认证流程
			async h5Auth() {
				const metaInfo = uni.getFacialRecognitionMetaInfo()
				
				this.$cloudOBjAjax('uni-face-recognition-co','getCertifyUrl',{
					realName: this.form.realName,
					idCard:this.form.idCard,
					metaInfo: JSON.stringify(metaInfo)
				}).then(res => {
					if (res.certifyUrl) {
						//获取CertifyUrl后跳转至认证页面
						window.location.href = res.certifyUrl;
					}
				}).catch(e => {
					uni.showToast({
						title: '认证失败，请稍后重试',
						icon: 'none'
					})
				})
			},

			// 小程序/App原生认证流程
			async nativeAuth() {
				try {
					// 获取设备信息
					const metaInfo = uni.getFacialRecognitionMetaInfo();

					// 调用云对象获取认证流水号
					const authCO = uniCloud.importObject('uni-face-recognition-co');
					const result = await authCO.getCertifyId({
						realName: this.form.realName.trim(),
						idCard: this.form.idCard.trim(),
						metaInfo: JSON.stringify(metaInfo)
					});

					if (result.success && result.certifyId) {
						console.log('获取认证流水号成功:', result.certifyId);

						// 调起原生刷脸界面
						await this.startNativeVerify(result.certifyId);

					} else {
						throw new Error(result.message || '获取认证流水号失败');
					}

				} catch (error) {
					console.error('原生认证失败:', error);
					this.showError(error.message || '认证初始化失败');
				}
			},

			// 调起原生刷脸界面
			startNativeVerify(certifyId) {
				return new Promise((resolve, reject) => {
					uni.startFacialRecognitionVerify({
						certifyId: certifyId,
						success: (res) => {
							console.log('原生认证成功:', res);
							this.authResult = {
								success: true,
								message: '认证成功',
								certifyId: certifyId
							};
							this.resultClass = 'success';

							// 查询最终认证结果
							this.queryFinalResult(certifyId);
							resolve(res);
						},
						fail: (err) => {
							console.log('原生认证失败:', err);
							this.authResult = {
								success: false,
								message: `认证失败: ${err.errMsg || '未知错误'}`,
								certifyId: certifyId
							};
							this.resultClass = 'error';
							reject(err);
						}
					});
				});
			},

			// H5环境获取设备信息 (模拟或使用浏览器信息)
			async getH5MetaInfo() {
				// 在H5环境，可能需要使用其他方式获取设备信息
				// 这里返回一个模拟的设备信息对象
				return {
					userAgent: navigator.userAgent,
					platform: navigator.platform,
					language: navigator.language,
					timestamp: Date.now(),
					screen: {
						width: screen.width,
						height: screen.height
					}
				};
			},

			// 检查H5回调参数
			checkH5Callback(options) {
				// #ifdef H5
				// 检查URL参数，判断是否是认证完成后的回调
				const urlParams = new URLSearchParams(window.location.search);
				const certifyId = urlParams.get('certifyId');
				const authStatus = urlParams.get('status');

				if (certifyId) {
					console.log('检测到认证回调参数:', {
						certifyId,
						authStatus
					});

					// 显示认证状态
					if (authStatus === 'success') {
						this.authResult = {
							success: true,
							message: '认证成功',
							certifyId: certifyId
						};
						this.resultClass = 'success';
					} else {
						this.authResult = {
							success: false,
							message: '认证失败',
							certifyId: certifyId
						};
						this.resultClass = 'error';
					}

					// 查询最终认证结果
					this.queryFinalResult(certifyId);

					// 清理URL参数 (可选)
					// this.cleanUrlParams();
				}
				// #endif
			},

			// 查询最终认证结果
			async queryFinalResult(certifyId) {
				try {
					const authCO = uniCloud.importObject('uni-face-recognition-co');
					const result = await authCO.getAuthResult({
						certifyId: certifyId
					});

					console.log('最终认证结果:', result);

					if (result.success) {
						// 认证成功，更新结果信息
						this.authResult = {
							...this.authResult,
							...result,
							message: result.message || '实名认证成功'
						};

						// 保存认证信息
						this.saveAuthInfo(result.data);

					} else {
						this.authResult = {
							...this.authResult,
							...result,
							message: result.message || '认证未通过'
						};
						this.resultClass = 'warning';
					}

				} catch (error) {
					console.error('查询最终结果失败:', error);
					// 即使查询失败，也不影响前端已显示的状态
				}
			},

			// 保存认证信息
			saveAuthInfo(authData) {
				const authInfo = {
					realName: this.form.realName,
					idCard: this.form.idCard,
					certifyId: this.authResult.certifyId,
					authTime: new Date(),
					authData: authData
				};

				// 保存到本地存储
				uni.setStorageSync('userAuthInfo', authInfo);

				// 触发认证成功事件
				uni.$emit('authSuccess', authInfo);

				uni.showToast({
					title: '实名认证成功',
					icon: 'success'
				});
			},

			// 清理URL参数 (H5专用)
			cleanUrlParams() {
				// 移除URL中的认证参数，避免刷新页面重复触发
				if (window.history.replaceState) {
					const newUrl = window.location.pathname;
					window.history.replaceState({}, document.title, newUrl);
				}
			},

			// 表单验证
			validateForm() {
				if (!this.form.realName || !this.form.realName.trim()) {
					this.showError('请输入姓名');
					return false;
				}

				if (!this.form.idCard || !this.form.idCard.trim()) {
					this.showError('请输入身份证号');
					return false;
				}

				// 身份证格式验证
				const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
				if (!idCardReg.test(this.form.idCard)) {
					this.showError('身份证号格式不正确');
					return false;
				}

				return true;
			},

			// 显示错误信息
			showError(message) {
				uni.showToast({
					title: message,
					icon: 'none',
					duration: 3000
				});
			}
		}
	}
</script>

<style scoped>
	.auth-container {
		padding: 40rpx 30rpx;
		min-height: 100vh;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	}

	.form-section {
		background: white;
		border-radius: 20rpx;
		padding: 40rpx 30rpx;
		margin-bottom: 40rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
	}

	.form-item {
		margin-bottom: 40rpx;
	}

	.label {
		display: block;
		font-size: 32rpx;
		color: #333;
		margin-bottom: 20rpx;
		font-weight: 500;
	}

	.input {
		border: 2rpx solid #e5e5e5;
		border-radius: 12rpx;
		padding: 24rpx;
		font-size: 32rpx;
		background: #fafafa;
		transition: all 0.3s;
	}

	.input:focus {
		border-color: #007AFF;
		background: white;
		box-shadow: 0 0 0 2rpx rgba(0, 122, 255, 0.2);
	}

	.auth-button {
		width: 100%;
		height: 90rpx;
		border-radius: 12rpx;
		font-size: 36rpx;
		font-weight: 500;
		background: linear-gradient(135deg, #007AFF, #0056CC);
		box-shadow: 0 8rpx 20rpx rgba(0, 122, 255, 0.3);
		margin-bottom: 40rpx;
		transition: all 0.3s;
	}

	.auth-button[disabled] {
		background: #cccccc;
		box-shadow: none;
		transform: none;
	}

	.auth-button:not([disabled]):active {
		transform: translateY(2rpx);
		box-shadow: 0 4rpx 10rpx rgba(0, 122, 255, 0.3);
	}

	.result-section {
		background: white;
		border-radius: 20rpx;
		padding: 40rpx 30rpx;
		margin-bottom: 40rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
	}

	.result-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
		text-align: center;
	}

	.result-content {
		font-size: 32rpx;
		text-align: center;
		padding: 30rpx;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		font-weight: 500;
	}

	.result-content.success {
		background: #e8f5e8;
		color: #4CAF50;
		border: 2rpx solid #4CAF50;
	}

	.result-content.error {
		background: #ffe8e8;
		color: #f44336;
		border: 2rpx solid #f44336;
	}

	.result-content.warning {
		background: #fff8e8;
		color: #ff9800;
		border: 2rpx solid #ff9800;
	}

	.result-detail {
		font-size: 28rpx;
		color: #666;
		text-align: center;
		word-break: break-all;
	}

	.platform-info {
		background: rgba(255, 255, 255, 0.9);
		border-radius: 12rpx;
		padding: 30rpx;
		text-align: center;
	}

	.info-text {
		display: block;
		font-size: 28rpx;
		color: #666;
		margin-bottom: 10rpx;
	}

	.info-text:last-child {
		margin-bottom: 0;
	}
</style>